#include "LogisticHeaderParser.h"

#include "PersonParser.h"
#include "RoleParser.h"
#include "EnterpriseParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

LogisticHeaderParser::LogisticHeaderParser(
    RoleParser *&_roleParser
    , EnterpriseParser *&_enterpriseParser
    , PersonParser *&_personParser
):    m_roleParser(_roleParser)
    , m_enterpriseParser(_enterpriseParser)
    , m_personParser(_personParser)
{

}

bool LogisticHeaderParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new LogisticHeader());

    /* Attributes */

    QStringRef data;

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("Role"))
        {
            if (!m_roleParser->parse(reader))
                return false;
            auto result = m_roleParser->result();
            m_result->roleList.append(result);
        }
        else if (name == QStringLiteral("Enterprise"))
        {
            if (!m_enterpriseParser->parse(reader))
                return false;
            auto result = m_enterpriseParser->result();
            m_result->enterpriseList.append(result);
        }
        else if (name == QStringLiteral("Person"))
        {
            if (!m_personParser->parse(reader))
                return false;
            auto result = m_personParser->result();
            m_result->personList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

LogisticHeader *LogisticHeaderParser::result()
{
    return m_result.take();
}

}